package com.erp.ae.controller;

import com.alibaba.fastjson.JSONObject;
import com.erp.ae.domain.bo.AeMsgSaveBo;
import com.erp.ae.service.IAeMsgSaveService;
import com.ruoyi.common.redis.config.RedisConfig;
import com.ruoyi.common.redis.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Handler;

@Slf4j
@RestController
@RequestMapping("erp/pushMessage")
public class PushMessageTestController {

    private static final String AE_MSG_KEY = "AE_MSG_ORDER_LIST";


    private static final String TEST_APP_KEY = "500890";
    private static final String TEST_APP_SECRET = "IEu1gaoOSF1TrrXBwXKBiM39i23gvQzW";
    //消息类型
    private static final String MESSAGE_TYPE = "message_type";

    @Resource
    IAeMsgSaveService aeMsgSaveService;

    /**
     * 接受GOP回调
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/receiveCallBack")
    public ResponseEntity<?> receiveGopCallback(HttpServletRequest request, @RequestBody String s) {
        JSONObject jsonObject = JSONObject.parseObject(s);

        AeMsgSaveBo msgSave = new AeMsgSaveBo();
        msgSave.setAeMsg(s);
        String data = jsonObject.getString("data");
        msgSave.setMsgData(data);
        if (jsonObject.getString("havana_id") != null) {
            msgSave.setHavanaId(jsonObject.getLong("havana_id"));
        }
        msgSave.setSellerId(jsonObject.getString("seller_id"));
        msgSave.setMessageType(jsonObject.getString("message_type"));
        msgSave.setMsgTimestamp(jsonObject.getLong("timestamp"));
        msgSave.setSite(jsonObject.getString("site"));
        msgSave.setProcessingStatus(0);
        JSONObject dataObject = JSONObject.parseObject(data);
        msgSave.setTradeOrderId(dataObject.getString("trade_order_id"));
        msgSave.setLoginId(dataObject.getString("login_id"));
        //保存信息
//        aeMsgSaveService.insertByBo(msgSave);
        log.info("PushMessageTestController receiveCallBack s:【{}】", s);

        String orderId = dataObject.getString("trade_order_id");
        //获取缓存中的商品
        String orderIds = RedisUtils.getCacheObject(AE_MSG_KEY);
        if (orderIds.equals("")){
            orderIds = orderId;
        }else {
            orderIds = orderIds + "," + orderId;
        }
        /** 放入redis中 */
        RedisUtils.setCacheObject(AE_MSG_KEY, orderIds);

        return ResponseEntity.ok("200");
    }

}
